package com.zcgame.base.utils

import android.content.Context
import android.content.SharedPreferences
import java.lang.IllegalArgumentException
import java.security.AccessControlContext
import kotlin.reflect.KProperty

@Suppress("UNCHECKED_CAST")
class MyPreference<T>(private val keyName:String, private val default: T, context: Context) {

    private val prefs:SharedPreferences by lazy {
        context.getSharedPreferences(keyName,Context.MODE_PRIVATE)
    }
    operator fun getValue(thisRef:Any?,property:KProperty<*>):T{
        return getSharePreferences(keyName,default)
    }
    operator fun setValue(thisRef: Any?,property: KProperty<*>,value: T){
        putSharePreferences(keyName,value)
    }

    private fun getSharePreferences(name: String, value: T):T =with(prefs){
        val res:Any? = when (value) {
            is Long -> getLong(name, value)
            is String -> getString(name, value)
            is Int -> getInt(name, value)
            is Boolean -> getBoolean(name, value)
            is Float -> getFloat(name, value)
            else -> throw IllegalArgumentException("Type Error, cannot be saved")
        }
        return res as T
    }

    private fun putSharePreferences(name: String, value: T) {
        prefs.edit().run {
            when(value){
                is Long -> putLong(name,value)
                is String -> putString(name,value)
                is Int -> putInt(name,value)
                is Boolean ->putBoolean(name,value)
                is Float ->putFloat(name,value)
                else -> throw IllegalArgumentException("Type Error, cannot be saved")
            }.apply()
        }
    }
}